package com.dstats.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by MeSeems - Note 1 on 22/01/2015.
 */
public class DatabaseOpenHelper extends SQLiteOpenHelper {

    public DatabaseOpenHelper(Context context) {
        super(context, AppDataContract.DATABASE_NAME, null, AppDataContract.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        createHeroesTable(sqLiteDatabase);
        createHeroRolesTable(sqLiteDatabase);
    }

    private void createHeroesTable(SQLiteDatabase db) {
        db.execSQL(String.format(
                "CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT)",
                AppDataContract.AppHeroEntry.TABLE_NAME,
                AppDataContract.AppHeroEntry._ID,
                AppDataContract.AppHeroEntry.NAME,
                AppDataContract.AppHeroEntry.LOCALIZED_NAME,
                AppDataContract.AppHeroEntry.BIO,
                AppDataContract.AppHeroEntry.ATK,
                AppDataContract.AppHeroEntry.ATK1));
    }

    private void createHeroRolesTable(SQLiteDatabase db) {
        db.execSQL(String.format(
                "CREATE TABLE %s (" +
                        "%s INTEGER, " +
                        "%s TEXT," +
                        "FOREIGN KEY(%s) REFERENCES %s(%s) ON DELETE CASCADE)",
                AppDataContract.AppHeroRolesEntry.TABLE_NAME,
                AppDataContract.AppHeroRolesEntry.HERO_ID,
                AppDataContract.AppHeroRolesEntry.ROLE,
                AppDataContract.AppHeroRolesEntry.HERO_ID,
                AppDataContract.AppHeroEntry.TABLE_NAME,
                AppDataContract.AppHeroEntry._ID));
    }
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
        dropAllTables(sqLiteDatabase);
        onCreate(sqLiteDatabase);
    }

    public void dropAllTables(SQLiteDatabase db) {
        dropHeroRolesTable(db);
        dropHeroTable(db);

    }
    void dropHeroTable(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + AppDataContract.AppHeroEntry.TABLE_NAME);
    }

    void dropHeroRolesTable(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + AppDataContract.AppHeroRolesEntry.TABLE_NAME);
    }

}
